import { request } from '@/utils/request'
import type {
  CreateUserParams as UserCreateForm,
  UpdateUserParams as UserUpdateForm,
  UserListParams as UserFilter,
  UserStats,
  ChangePasswordParams as ChangePasswordForm
} from '@/types/user'

const buildUserQuery = (filters?: UserFilter) => {
  const {
    page,
    size,
    skip,
    limit,
    search,
    username,
    email,
    phone,
    status,
    role,
    department,
    sort_by,
    sort_order
  } = filters || {}

  const preferredSize = Number.isFinite(size) ? Number(size) : Number.isFinite(limit) ? Number(limit) : 20
  const normalizedSize = preferredSize > 0 ? preferredSize : 20

  const hasSkip = Number.isFinite(skip)
  const resolvedPage = Number.isFinite(page)
    ? Math.max(1, Number(page))
    : hasSkip
      ? Math.max(1, Math.floor(Number(skip) / normalizedSize) + 1)
      : 1
  const resolvedSkip = hasSkip ? Number(skip) : (resolvedPage - 1) * normalizedSize

  const searchTokens: string[] = []
  ;[search, username, email, phone].forEach(value => {
    if (typeof value === 'string') {
      const trimmed = value.trim()
      if (trimmed) {
        trimmed.split(/\s+/).forEach(token => {
          if (token) {
            searchTokens.push(token)
          }
        })
      }
    }
  })

  const finalSearch = searchTokens.length > 0 ? Array.from(new Set(searchTokens)).join(' ') : undefined

  const query: Record<string, any> = {
    skip: resolvedSkip < 0 ? 0 : resolvedSkip,
    limit: normalizedSize,
    sort_by: sort_by || 'created_at',
    sort_order: sort_order || 'desc'
  }

  if (finalSearch) {
    query.search = finalSearch
  }
  if (status) {
    query.status = status
  }
  if (role) {
    query.role = role
  }
  if (department) {
    query.department = department
  }

  return {
    query,
    page: resolvedPage,
    size: normalizedSize
  }
}

// 用户管理相关API

// 获取用户列表
export function getUserList(params?: UserFilter) {
  const { query } = buildUserQuery(params)
  return request({
    url: '/users',
    method: 'get',
    params: query
  })
}

// 获取用户列表 (别名，为了兼容其他文件的导入)
export const getUsers = getUserList

// 获取用户总数
export function getUserCount(filters?: UserFilter) {
  const { query } = buildUserQuery(filters)
  const countParams: Record<string, any> = {}

  if (query.search) {
    countParams.search = query.search
  }
  if (query.status) {
    countParams.status = query.status
  }
  if (query.role) {
    countParams.role = query.role
  }
  if (query.department) {
    countParams.department = query.department
  }

  return request({
    url: '/users/count',
    method: 'get',
    params: countParams
  })
}

// 获取用户统计信息
export function getUserStats(): Promise<UserStats> {
  return request({
    url: '/users/stats',
    method: 'get'
  }).then(response => {
    // response是axios响应对象，需要从response.data中获取API响应数据
    const apiResponse = response.data
    
    // 处理统一响应格式 {success, code, message, data, timestamp}
    if (apiResponse && apiResponse.success && apiResponse.data) {
      const data = apiResponse.data
      return {
        total_users: data.total_users || 0,
        active_users: data.active_users || 0,
        inactive_users: data.inactive_users || 0,
        new_users_this_month: data.new_users_this_month || 0,
        user_growth_rate: data.user_growth_rate || 0
      }
    }
    
    // 如果响应格式不正确或失败，返回默认值
    console.warn('获取用户统计信息响应格式异常:', apiResponse)
    return {
      total_users: 0,
      active_users: 0,
      inactive_users: 0,
      new_users_this_month: 0,
      user_growth_rate: 0
    }
  }).catch(error => {
    console.error('获取用户统计信息失败:', error)
    
    // 返回默认的统计数据，确保界面不会崩溃
    return {
      total_users: 0,
      active_users: 0,
      inactive_users: 0,
      new_users_this_month: 0,
      user_growth_rate: 0
    }
  })
}

// 获取用户详情
export function getUserDetail(id: string) {
  return request({
    url: `/users/${id}`,
    method: 'get'
  })
}

// 创建用户
export function createUser(data: UserCreateForm) {
  return request({
    url: '/users',
    method: 'post',
    data
  })
}

// 更新用户
export function updateUser(id: string, data: UserUpdateForm) {
  return request({
    url: `/users/${id}`,
    method: 'put',
    data
  })
}

// 删除用户
export function deleteUser(id: string) {
  return request({
    url: `/users/${id}`,
    method: 'delete'
  })
}

// 批量删除用户
export function batchDeleteUsers(ids: string[]) {
  return request({
    url: '/users/batch-delete',
    method: 'post',
    data: { ids }
  })
}

// 激活/停用用户
export function toggleUserStatus(id: string) {
  return request({
    url: `/users/${id}/status`,
    method: 'patch'
  })
}

// 批量激活用户
export function batchActivateUsers(ids: string[]) {
  return request({
    url: '/users/batch-activate',
    method: 'post',
    data: { ids }
  })
}

// 批量停用用户
export function batchDeactivateUsers(ids: string[]) {
  return request({
    url: '/users/batch-deactivate',
    method: 'post',
    data: { ids }
  })
}

// 重置用户密码
export function resetUserPassword(id: string, newPassword: string) {
  return request({
    url: `/users/${id}/reset-password`,
    method: 'post',
    data: { new_password: newPassword }
  })
}

// 修改用户密码
export function changeUserPassword(id: string, data: ChangePasswordForm) {
  return request({
    url: `/users/${id}/change-password`,
    method: 'post',
    data
  })
}

// 分配角色给用户
export function assignRolesToUser(id: string, roleIds: string[]) {
  return request({
    url: `/users/${id}/roles`,
    method: 'post',
    data: { role_ids: roleIds }
  })
}

// 批量分配角色
export function batchAssignRoles(userIds: string[], roleIds: string[]) {
  return request({
    url: '/users/batch-assign-roles',
    method: 'post',
    data: { user_ids: userIds, role_ids: roleIds }
  })
}

// 获取用户权限
export function getUserPermissions(id: string) {
  return request({
    url: `/users/${id}/permissions`,
    method: 'get'
  })
}

// 获取可用的用户角色代码（用于权限不足时的回退）
export async function getUserRoleCodes(): Promise<string[]> {
  try {
    const response = await request({
      url: '/users/roles/list',
      method: 'get'
    })

    const payload = response.data

    if (payload?.success && payload.data) {
      if (Array.isArray(payload.data)) {
        return payload.data as string[]
      }
      if (Array.isArray((payload.data as any).roles)) {
        return (payload.data as any).roles as string[]
      }
    }

    if (Array.isArray(payload?.roles)) {
      return payload.roles as string[]
    }

    return []
  } catch (error) {
    console.error('获取角色代码列表失败:', error)
    return []
  }
}

// 导出用户数据
export function exportUsers(filters?: UserFilter) {
  return request({
    url: '/users/export',
    method: 'get',
    params: filters,
    responseType: 'blob'
  }).then(response => {
    // 直接返回blob数据
    return response.data
  })
}

// 导入用户数据
export function importUsers(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/users/import',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 角色管理相关API

// 获取角色列表
export function getRoleList(params?: {
  page?: number
  size?: number
  search?: string
}) {
  return request({
    url: '/roles',
    method: 'get',
    params
  })
}

// 获取所有角色（不分页）
export function getAllRoles() {
  return request({
    url: '/roles/all',
    method: 'get'
  })
}

// 创建角色
export function createRole(data: {
  name: string
  description?: string
  permissions: string[]
}) {
  return request({
    url: '/roles',
    method: 'post',
    data
  })
}

// 更新角色
export function updateRole(id: string, data: {
  name?: string
  description?: string
  permissions?: string[]
}) {
  return request({
    url: `/roles/${id}`,
    method: 'put',
    data
  })
}

// 删除角色
export function deleteRole(id: string) {
  return request({
    url: `/roles/${id}`,
    method: 'delete'
  })
}

// 权限管理相关API

// 获取权限列表
export function getPermissionList() {
  return request({
    url: '/permissions',
    method: 'get'
  })
}

// 获取权限树
export function getPermissionTree() {
  return request({
    url: '/permissions/tree',
    method: 'get'
  })
}

// 获取权限模块
export function getPermissionModules() {
  return request({
    url: '/permissions/modules',
    method: 'get'
  })
}

// 获取权限定义
export function getPermissionDefinitions() {
  return request({
    url: '/permissions/definitions',
    method: 'get'
  })
}

// 获取权限级别
export function getPermissionLevels() {
  return request({
    url: '/permissions/levels',
    method: 'get'
  })
}

// 部门管理相关API

// 获取部门列表
export function getDepartmentList() {
  return request({
    url: '/departments',
    method: 'get'
  })
}

// 获取部门树
export function getDepartmentTree() {
  return request({
    url: '/departments/tree',
    method: 'get'
  })
}

// 在线用户相关API

// 获取在线用户列表
export function getOnlineUsers() {
  return request({
    url: '/users/online',
    method: 'get'
  })
}

// 强制用户下线
export function forceUserOffline(id: string) {
  return request({
    url: `/users/${id}/force-offline`,
    method: 'post'
  })
}

// 用户活动日志
export function getUserActivityLogs(id: string, params?: {
  page?: number
  size?: number
  start_date?: string
  end_date?: string
}) {
  return request({
    url: `/users/${id}/activity-logs`,
    method: 'get',
    params
  })
}